package GUI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.TitledBorder;

import DataObjects.ConstantObjects;
import DataObjects.Item;
import DataObjects.RecipeLeftList;
import Messages.MessageAddNewInventoryItem;
import Messages.MessageAddNewInventoryItemReply;
import Messages.MessageCheckExistsItems;
import Messages.MessageCheckExistsItemsReply;

import java.awt.BorderLayout;
import java.io.IOException;
import java.util.Vector;

public class PfAdd_new_item_from_new_recipe extends JFrame {
	
	JPanel infoPanel;
	JTextField textField_id;
	JTextField textField_name;
	JComboBox categoryCB;
	JComboBox statusCB;
	JComboBox measureCB;
	JTextField textField_minAmount;
	JTextField textField_maxAmount;
	JTextField textField_measure;
	JTextField textField_expDate;
	JTextField textField_amount;
	JTextField textField_price;
	JButton saveButt;
	JLabel goodLbl;
	JLabel goodLbl2;
	JPanel checkPanel;
	JPanel buttonsPanel;
	
	private Vector <RecipeLeftList> res_allItems;
	private DefaultListModel allItemsModel;
	
	private MainMenu mainMenu;
	private String itemID;
	
	
	
	private int newId;
	
	public PfAdd_new_item_from_new_recipe(MainMenu mm,String itemID,Vector <RecipeLeftList> res_allItems,DefaultListModel allItemsModel)
	{
		super();
		this.res_allItems=res_allItems;
		this.allItemsModel=allItemsModel;
		this.mainMenu=mm;
		this.itemID=itemID;
		
		newId=Integer.parseInt(itemID);	
		newId=newId+1;	
		this.setSize(614, 544);
		getContentPane().setLayout(null);
		initialize();
		this.setVisible(true);
	}
	
	public void initialize()
	{
		  Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize();
		  this.setLocation((sSize.width-this.getWidth())/2,(sSize.height-this.getHeight())/2);
		  getContentPane().add(getDetailsPanel());
		  getContentPane().add(getCheckInputPanel());
		  getContentPane().add(getButtonsPanel(this));
		 
		 
		  
		  
		 
	}

	
	public JPanel getDetailsPanel()
	{
		
		infoPanel=new JPanel();
		infoPanel.setSize(598, 398);
		infoPanel.setLocation(0, 0);
		infoPanel.setBackground(new Color(255, 250, 205));
		infoPanel.setForeground(new Color(0, 0, 0));
		infoPanel.setBorder(new TitledBorder(null, "נתונים של פריט", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		SpringLayout sl_infoPanel = new SpringLayout();
		infoPanel.setLayout(sl_infoPanel);
		
		textField_id = new JTextField();
		textField_id.setHorizontalAlignment(JTextField.RIGHT);
		textField_id.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_id.setText(Integer.toString(newId));
		textField_id.setColumns(10);
		textField_id.setEditable(false);
		JLabel sid = new JLabel("מספר פריט :", JLabel.TRAILING);
		sid.setFont(new Font("Tahoma", Font.BOLD, 12));
		sid.setForeground(new Color(25, 25, 112));
		sid.setLabelFor(textField_id);
		infoPanel.add(textField_id);
		infoPanel.add(sid);
		
		textField_name = new JTextField();
		sl_infoPanel.putConstraint(SpringLayout.NORTH, textField_id, 17, SpringLayout.SOUTH, textField_name);
		sl_infoPanel.putConstraint(SpringLayout.EAST, textField_id, 0, SpringLayout.EAST, textField_name);
		textField_name.setHorizontalAlignment(JTextField.RIGHT);
		textField_name.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_name.setColumns(10);		
		JLabel name = new JLabel("שם פריט :", JLabel.TRAILING);
		name.setForeground(new Color(75, 0, 130));
		name.setFont(new Font("Tahoma", Font.BOLD, 12));
		name.setLabelFor(textField_name);	
		infoPanel.add(textField_name);
		infoPanel.add(name);
		

		String[] strs = new ConstantObjects().getItemCategories();

		categoryCB = new JComboBox(strs);
		JLabel labelCategory = new JLabel("סוג של פריט :", JLabel.TRAILING);
		labelCategory.setForeground(new Color(75, 0, 130));
		labelCategory.setFont(new Font("Tahoma", Font.BOLD, 12));
		labelCategory.setLabelFor(categoryCB);
		infoPanel.add(categoryCB);
		infoPanel.add(labelCategory);
	   	
		textField_minAmount = new JTextField();
		textField_minAmount.setHorizontalAlignment(JTextField.RIGHT);
		textField_minAmount.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_minAmount.setColumns(10);
		JLabel label_1 = new JLabel("כמות מינימלית :", JLabel.TRAILING);
		label_1.setForeground(new Color(75, 0, 130));
		label_1.setFont(new Font("Tahoma", Font.BOLD, 12));
		label_1.setLabelFor(textField_minAmount);
		infoPanel.add(textField_minAmount);
		infoPanel.add(label_1);	
	   
		textField_maxAmount = new JTextField();
		textField_maxAmount.setHorizontalAlignment(JTextField.RIGHT);
		textField_maxAmount.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_maxAmount.setColumns(10);
		JLabel label_2 = new JLabel("כמות מקסימלית:", JLabel.TRAILING);
		label_2.setFont(new Font("Tahoma", Font.BOLD, 12));
		label_2.setForeground(new Color(75, 0, 130));
		label_2.setLabelFor(textField_maxAmount);	
		infoPanel.add(textField_maxAmount);
		infoPanel.add(label_2);
		
		/*textField_measure = new JTextField();
		textField_measure.setHorizontalAlignment(JTextField.RIGHT);
		textField_measure.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_measure.setColumns(10);
		JLabel lblZip = new JLabel("יח' מדידה:", JLabel.TRAILING);
		lblZip.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblZip.setForeground(new Color(75, 0, 130));
		lblZip.setLabelFor(textField_measure);
		infoPanel.add(textField_measure);
		infoPanel.add(lblZip);*/
		String[] msrUnits = new ConstantObjects().getMeasureUnit();
		
		measureCB=new JComboBox(msrUnits);			 
		  JLabel lblZip = new JLabel("יח' מדידה:", JLabel.TRAILING);
		lblZip.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblZip.setForeground(new Color(75, 0, 130));
		lblZip.setLabelFor(textField_measure);
		 infoPanel.add(measureCB);	
		 infoPanel.add(lblZip);
		
		
		 
		textField_expDate = new JTextField();
		textField_expDate.setHorizontalAlignment(JTextField.RIGHT);
		textField_expDate.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_expDate.setColumns(10);
		JLabel lblContactMen = new JLabel("תאריך תפוגה:", JLabel.TRAILING);
		lblContactMen.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblContactMen.setForeground(new Color(75, 0, 130));
		lblContactMen.setLabelFor(textField_expDate);
		infoPanel.add(textField_expDate);
		infoPanel.add(lblContactMen);

			
		textField_price = new JTextField();
		textField_price.setHorizontalAlignment(JTextField.RIGHT);
		textField_price.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textField_price.setColumns(10);
		JLabel label_4 = new JLabel("מחיר:", JLabel.TRAILING);
		label_4.setFont(new Font("Tahoma", Font.BOLD, 12));
		label_4.setForeground(new Color(75, 0, 130));
		label_4.setLabelFor(textField_price);
		infoPanel.add(textField_price);
		infoPanel.add(label_4);
		
		 statusCB=new JComboBox();			 
		 JLabel label_status=new JLabel("סוג פריט", JLabel.TRAILING);
		 label_status.setLabelFor(statusCB);
		 infoPanel.add(statusCB);	
		 infoPanel.add(label_status);
		 statusCB.setVisible(false);
		 label_status.setVisible(false);

	SpringUtilities.makeCompactGrid(infoPanel, 8, 2, //rows, cols
			     200, 10, //initX, initY
			        80, 10); //xPad, yPad
		
		return infoPanel;
	}
	
	
	public JPanel getButtonsPanel(PfAdd_new_item_from_new_recipe addNewItem )
	{
		final PfAdd_new_item_from_new_recipe addNewItems;
		addNewItems=addNewItem;
	    buttonsPanel = new JPanel();
		buttonsPanel.setSize(588, 50);
		buttonsPanel.setLocation(0, 397);
		buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,5));
		
		buttonsPanel.add(getSaveButton());
		buttonsPanel.add( getCancelButton(addNewItems));
		return buttonsPanel;
	}
	
	public JButton getSaveButton()
	{
		saveButt = new JButton("שמור");
			
		saveButt.setPreferredSize(new Dimension(70, 40));
		saveButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				JButton btnSave=(JButton) e.getSource();	
				checkPanel.removeAll();			
				Vector<String> checkingResult=inputCheck();
				Vector<Vector> weekHours=new Vector<Vector>();
				int size=checkingResult.size();    
				JLabel goodLbl=new JLabel("כל הנתונים תקינים");
				goodLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
				goodLbl.setForeground(Color.blue);
				goodLbl.setAlignmentX(goodLbl.CENTER_ALIGNMENT);
				
			   
				
				if(size==0)
				{
					
					checkPanel.add(goodLbl);
					checkPanel.validate();
					Item item =new Item();
					item.setIname(textField_name.getText());
					
				if(categoryCB.getSelectedItem() != null)
					item.setICategory(categoryCB.getSelectedItem().toString());
					else
						item.setICategory(categoryCB.getItemAt(0).toString());
					
					item.setIid(textField_id.getText());
					item.setIExpiration(textField_expDate.getText());
					item.setIMax_quantity(textField_maxAmount.getText());
					item.setIMin_quantity(textField_minAmount.getText());
					item.setIUnit_of_measure((String) measureCB.getSelectedItem());
					item.setIcost(textField_price.getText());
					
					MessageCheckExistsItems msgCheckItem= new MessageCheckExistsItems(item);
					try {
						mainMenu.ms.client.sendToServer(msgCheckItem);
						MessageCheckExistsItemsReply resultFlag=(MessageCheckExistsItemsReply)mainMenu.ms.client.GetMessage();
						checkPanel.removeAll();	
						if (resultFlag.getCheckFlag()==1) 
						{
							
							goodLbl2=new JLabel("שם קיים");
							goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
							goodLbl2.setForeground(Color.red);
							goodLbl2.setAlignmentX(goodLbl2.CENTER_ALIGNMENT);
							checkPanel.add(goodLbl2);
							checkPanel.validate();
							return;
							
						}
					}
					catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}	
					  
					 MessageAddNewInventoryItem msgNewItem= new MessageAddNewInventoryItem(item);
					 
					 try {
							mainMenu.ms.client.sendToServer(msgNewItem);
							MessageAddNewInventoryItemReply result=(MessageAddNewInventoryItemReply)mainMenu.ms.client.GetMessage();
						
							
							if (result.getResult()) 
							{
								RecipeLeftList row = new RecipeLeftList();
								String flag = "right";
							    getCheckSavePanel(flag);
								checkPanel.add(goodLbl2);
								checkPanel.validate();
								row.setItemID(Integer.parseInt(item.getIid()));
								row.setItemName(item.getIname());
								row.setiCategory(item.getICategory());
								row.setiExpiration(item.getIExpiration());
								row.setiMin(Float.parseFloat(item.getIMin_quantity()));
								row.setiMax(Float.parseFloat(item.getIMax_quantity()));
								row.setIUnit_of_measure(item.getIUnit_of_measure());
								row.setiCost(Float.parseFloat(item.getIcost()));
								res_allItems.add(row);
								allItemsModel.addElement(item.getIname());
								
								
							
							}
							else
							{
								String flag = "wrong";
								getCheckSavePanel(flag);
								checkPanel.add(goodLbl2);
								checkPanel.validate();
							}
							
							
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
										
					

					
					
				}
				
				
				else  //wrong input-print all errors on check_panel
				{
					checkPanel.removeAll();
					JLabel wrongLbl=new JLabel("תהליך הוספת פריט נכשל :");
					wrongLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
					wrongLbl.setForeground(Color.red);
					wrongLbl.setAlignmentX(wrongLbl.RIGHT_ALIGNMENT);
					checkPanel.add(wrongLbl);
					
					for(int i=0;i<size;i++)
					{
						JLabel error=new JLabel(checkingResult.get(i));
						error.setForeground(Color.red);
						error.setAlignmentX(wrongLbl.RIGHT_ALIGNMENT);
						checkPanel.add(error);
					}
					checkPanel.validate();
				}
				
					
				
				
				
		
			}
		});
		return saveButt;
	}
	
	public JButton getCancelButton(PfAdd_new_item_from_new_recipe addNewItem)
	{
		final PfAdd_new_item_from_new_recipe addNewItems;
		addNewItems=addNewItem;
		JButton cancelButt = new JButton("ביטול");
		cancelButt.setPreferredSize(new Dimension(70, 40));
		cancelButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				addNewItems.dispose();
			}
		});
		return cancelButt;
	}
	
	
	public void getCheckSavePanel(String flag)
	{
				
		String checkFlag=flag;
	if(checkFlag.equals("right"))
		{
	    goodLbl2=new JLabel("הפריט נשמר בהצלחה");
		goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
		goodLbl2.setForeground(Color.blue);
		goodLbl2.setAlignmentX(goodLbl2.CENTER_ALIGNMENT);
	
		}
		else
		{
		    goodLbl2=new JLabel("בעיית תקשורת.הנתונים לא נשמר");
			goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
			goodLbl2.setForeground(Color.blue);
			goodLbl2.setAlignmentX(goodLbl2.CENTER_ALIGNMENT);
		
		}
				
		
	}
	
	public JPanel getCheckInputPanel()
	{
		
	    checkPanel = new JPanel();
		checkPanel.setLayout(new BoxLayout(checkPanel, BoxLayout.Y_AXIS) );
		checkPanel.setSize(588, 48);
		checkPanel.setLocation(0, 447);
					
		
		
		return checkPanel;
	}
	
	
	
	
	 private Vector <String> inputCheck()
	 
	 {
		 checkPanel.removeAll();
		 Vector<String> result=new Vector<String>();
		 
		 
//=================================================check for name================================
	      
	     String name=textField_name.getText();
	     if(name.length()==0) result.add("יש להקיש שם ");
	    
	     
	
	     
//=============================================check for quantityMin ======================
	     
	     String quantityMin=textField_minAmount.getText();
	     if(quantityMin.length()==0) result.add("יש להקיש כמות מינימלית");
	     else
	     {
	    	 for(int i=0;i<quantityMin.length();i++)
	    	 {
	    		 if (quantityMin.charAt(i)<'0'|| quantityMin.charAt(i)>'9')
	    		 {
	    			 result.add("כמות אינה תקינה");
	    			 break;
	    		 }	    		 
	    	 }
	     }
//=============================================check for quantityMax ======================
	     
	     String quantityMax=textField_maxAmount.getText();
	     if(quantityMin.length()==0) result.add("יש להקיש כמות מקסימלית");
	     else
	     {
	    	 for(int i=0;i<quantityMax.length();i++)
	    	 {
	    		 if (quantityMax.charAt(i)<'0'|| quantityMin.charAt(i)>'9')
	    		 {
	    			 result.add("כמות אינה תקינה");
	    			 break;
	    		 }	    		 
	    	 }
	     }	 
	     
//=============================================check for units ======================
	     
	    /* String unitsMeasure=textField_measure.getText();
	     if(unitsMeasure.length()==0) result.add("יש להקיש יח' מדידה");
	     else
	     {
	    	 for(int i=0;i<unitsMeasure.length();i++)
	    	 {
	    		 if (unitsMeasure.charAt(i)<'א'|| unitsMeasure.charAt(i)>'ת')
	    		 {
	    			 result.add("יח' מדידה אינם תקינות");
	    			 break;
	    		 }	    		 
	    	 }
	     }	 */
	     
	     
//=============================================check for expiration ======================
	     
	     String expir=textField_expDate.getText();
	     if(expir.length()==0) result.add("יש להקיש תפוגה");
	     else
	     {
	    	 for(int i=0;i<expir.length();i++)
	    	 {
	    		 if (expir.charAt(i)<'0'|| expir.charAt(i)>'9')
	    		 {
	    			 result.add("תפוגה אינה תקינה");
	    			 break;
	    		 }	    		 
	    	 }
	     }	 	     
	     
//=============================================check for price ======================
	     
	     String price=textField_price.getText();
	     if(price.length()==0) result.add("יש להקיש מחיר");
	     else
	     {
	    	 for(int i=0;i<price.length();i++)
	    	 {
	    		 if (price.charAt(i)<'0'|| price.charAt(i)>'9')
	    		 {
	    			 result.add("מחיר אינו תקין");
	    			 break;
	    		 }	    		 
	    	 }
	     }	 	          
	     
	     

     
		 return result;
		 
	 }
}
